package com.wty.mianshi.recursion;


import com.wty.mianshi.common.Node;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 反转链表
 */
public class LinkedListReverse {


    public <T> Node<T> reverseLinkedList(Node<T> head){

        if(head==null||head.getNext()==null){
            return head;
        }

        //假设后面的是反转好的
        Node newHead=reverseLinkedList(head.getNext());
        head.getNext().setNext(head);
        head.setNext(null);
        return newHead;
    }


    public void printLinkedList(Node node){
        while (node!=null){
            System.out.print(node.getData());
            System.out.print(" ");
            node=node.getNext();
        }
        System.out.println();
    }




    public static void main(String args[]){
        LinkedListCreator linkedListCreator=new LinkedListCreator();
        LinkedListReverse linkedListReverse=new LinkedListReverse();

        Node node1=linkedListReverse.reverseLinkedList(linkedListCreator.createNode(new ArrayList<Integer>()));
        linkedListCreator.printLinkedList(node1);

        Node node2=linkedListReverse.reverseLinkedList(linkedListCreator.createNode(Arrays.asList(1)));
        linkedListCreator.printLinkedList(node2);
        Node node3=linkedListReverse.reverseLinkedList(linkedListCreator.createNode(Arrays.asList(1,2,3,4,5)));
        linkedListCreator.printLinkedList(node3);
    }
}
